package com.tools.commons.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie 工具类
 */
public final class CookieUtils {
    protected static final Logger logger = LoggerFactory.getLogger(CookieUtils.class);

    private CookieUtils() {
    }

    public static String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookieList = request.getCookies();
        if (cookieList == null || cookieName == null) {
            return null;
        }
        for (Cookie cookie : cookieList) {
            if (cookie.getName().equals(cookieName)) {
                return cookie.getValue();
            }
        }
        return null;
    }

    /**
     * 设置Cookie的值 不设置生效时间默认浏览器关闭即失效
     */
    public static void setCookie(HttpServletResponse response, String cookieName, String cookieValue) {
        setCookie(response, cookieName, cookieValue, -1);
    }

    /**
     * 设置Cookie的值 在指定时间内生效
     */
    public static void setCookie(HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge) {
        doSetCookie(response, cookieName, cookieValue, cookieMaxAge);
    }

    public static void deleteCookie(HttpServletResponse response, String cookieName) {
        doSetCookie(response, cookieName, "", -1);
    }


    private static void doSetCookie(HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxAge) {
        Cookie cookie = new Cookie(cookieName, cookieValue);
        if (cookieMaxAge > 0)
            cookie.setMaxAge(cookieMaxAge);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
